<?php

namespace App\Services\Admin\Ranch;

use App\Exceptions\RanchException;
use App\Models\Store\User\UserApplyRecordsModel;
use App\Models\Store\User\UserModel;
use Exception;
use Illuminate\Support\Facades\DB;

class ApplyService extends BaseRanchService
{

    const STATUS_APPROVED = 1; // 审核通过
    const STATUS_REJECTED = 2; // 审核通过

    /**
     * 申请列表
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function list(array $params): array
    {
        $total = $this->getUserApplyRecordsModel()->total($params);

        // 申请列表
        $applyRecordsList = $this->getUserApplyRecordsModel()->list($params, [
            'store_user_apply_records.id', 'store_user_apply_records.store_user_id',
            'store_user_apply_records.status'
        ]);

        $userIds = array_column($applyRecordsList, 'store_user_id');

        // 查询用户信息
        $userList = $this->getStoreUserModel()->getItemsByIds($userIds, [
            'id', 'phone', 'real_name', 'avatar'
        ]);
        $userListMap = array_column($userList, null, 'id');

        // 查询查询用户牧场列表
        $ranchList = $this->getStoreRanchModel()->getItemsByStoreUserIds($userIds, [
            'id', 'store_user_id', 'name'
        ]);
        $ranchListMap = array_column($ranchList, null, 'store_user_id');

        $list = [];
        foreach ($applyRecordsList as $item) {
            $list[] = [
                'id' => $item['id'],
                'userId' => $item['store_user_id'],
                'phone' => $userListMap[$item['store_user_id']]['phone'],
                'realName' => $userListMap[$item['store_user_id']]['real_name'],
                'avatar' => $userListMap[$item['store_user_id']]['avatar'],
                'ranchName' => $ranchListMap[$item['store_user_id']]['name'],
                'status' => $item['status']
            ];
        }

        return [
            'total' => $total,
            'list' => $list,
        ];
    }

    /**
     * 申请详情
     * @param array $params
     * @return array
     * @throws RanchException
     * @throws Exception
     */
    public function detail(array $params): array
    {
        // 查询详情
        $detail = $this->getUserApplyRecordsModel()->getItemById($params['id'], [
            'id', 'store_user_id'
        ]);
        if (empty($detail)) {
            throw new RanchException("牧场不存在", RanchException::CODE_1001);
        }

        // 查询用户信息
        $userData = $this->getStoreUserModel()->getItemById($detail['store_user_id'], [
            'id', 'phone', 'real_name', 'avatar', 'id_card'
        ]);

        // 查询用户身份信息
        $userIdCardData = $this->getStoreUserIdCardModel()->getItemByStoreUserId($userData['id'], [
            'id', 'front_img_url', 'back_img_url'
        ]);

        // 查询牧场信息
        $ranchData = $this->getStoreRanchModel()->getItemsByStoreUserId($userData['id'], [
            'id', 'store_user_id', 'name', 'province_id', 'city_id', 'region_id', 'address'
        ]);

        // 查询地区
        $areaIds = [$ranchData['province_id'], $ranchData['city_id'], $ranchData['region_id']];
        $areaList = $this->getAreaModel()->getAreaNameListByCodeList($areaIds);
        $areaListMap = array_column($areaList, 'name', 'code');
        $areaName = $this->getAreaName($areaListMap[$ranchData['province_id']], $areaListMap[$ranchData['city_id']], $areaListMap[$ranchData['region_id']]);
        return [
            'id' => $detail['id'],
            'userId' => $userData['id'],
            'phone' => $userData['phone'],
            'realName' => $userData['real_name'],
            'avatar' => $userData['avatar'],
            'idCard' => $userData['id_card'],
            'fontImgUrl' => $userIdCardData['front_img_url'],
            'backImgUrl' => $userIdCardData['back_img_url'],
            'ranchName' => $ranchData['name'],
            'address' => $areaName . ' ' . $ranchData['address'],
        ];
    }

    /**
     * 操作审核
     * @param array $params
     * @return void
     * @throws RanchException
     * @throws Exception
     */
    public function apply(array $params)
    {
        // 查询详情
        $detail = $this->getUserApplyRecordsModel()->getItemById($params['id'], [
            'id', 'store_user_id', 'status'
        ]);
        if (empty($detail)) {
            throw new RanchException("牧场不存在", RanchException::CODE_1001);
        }
        if ($detail['status'] != UserApplyRecordsModel::STATUS_WAIT) {
            throw new RanchException("该状态不允许操作", RanchException::CODE_1002);
        }

        $updateUser = [];
        $updateUserApplyRecords = [];
        switch ($params['status']) {
            case self::STATUS_APPROVED:
                $updateUser['status'] = UserModel::STATUS_DEFAULT;
                $updateUserApplyRecords['status'] = UserApplyRecordsModel::STATUS_APPROVED;
                break;
            case self::STATUS_REJECTED:
                $updateUserApplyRecords['status'] = UserApplyRecordsModel::STATUS_REJECTED;
                break;
        }

        // 操作审核
        DB::transaction(function () use ($detail, $updateUser, $updateUserApplyRecords) {
            // 更新用户状态
            $updateUser && $this->getStoreUserModel()->updateItemById($detail['store_user_id'], $updateUser);
            // 更新审核记录状态
            $updateUserApplyRecords && $this->getUserApplyRecordsModel()->updateItemById($detail['id'], $updateUserApplyRecords);
        });

    }
}
